package utils

import (
	"database/sql"
	"github.com/beego/beego/v2/client/orm"
	beego "github.com/beego/beego/v2/server/web"
	_ "github.com/go-sql-driver/mysql"
)

/**
 *@author:zhengyilong
 *@email:1797344574@qq.com
 *@phone:13479394730
 *@DateTime:2021/12/17 14:21
 **/

//定义一个全部变量，存放连接对象
var db *sql.DB

//连接数据库
func ConnectDB() {
	conf := beego.AppConfig

	//通过Beego框架读取配置文件中的相关信息
	username, _ := conf.String("username")
	password, _ := conf.String("password")
	mysqlhost, _ := conf.String("mysqlhost")
	mysqlport, _ := conf.String("mysqlport")
	databasename, _ := conf.String("databasename")
	drivername, _ := conf.String("drivername")

	//orm对象关系映射
	orm.RegisterDriver(drivername,orm.DRMySQL)

	dbConnStr := username + ":" + password + "@tcp(" + mysqlhost + ":" + mysqlport + ")/" + databasename + "?charset=utf8"
	open, err := sql.Open(drivername, dbConnStr)
	if err!=nil{
		//fmt.Println("数据库连接失败：",err)
		LogError("数据库连接失败："+err.Error())
		return
	}
	db = open
	LogInfo("数据库连接成功")
}

//查询全部数据
func FindObjects(sql string, args ...interface{}) (*sql.Rows,error) {
	result, err := db.Query(sql, args...)
	if err != nil {
		//fmt.Println("查询失败，查询语句："+sql)
		LogError("查询失败，查询语句："+sql)
		return nil, err
	}
	return result,nil
}

//查询单条数据
func FindObject(sql string, args ...interface{}) *sql.Row {
	return db.QueryRow(sql,args...)
}

//增删改操作
func ExecTable(sql string, args ...interface{}) (cont, id int64, err error) {
	exec, err := db.Exec(sql, args...)
	if err != nil {
		//fmt.Println("执行指定的SQL语句发生错误，SQL：",sql)
		LogError("执行指定的SQL语句发生错误，SQL："+sql)
		return 0,0,err
	}

	cont, err = exec.RowsAffected()
	if err != nil {
		//fmt.Println("获取此SQL语句执行后所影响的行数时发生错误")
		LogError("获取此SQL语句执行后所影响的行数时发生错误")
		return 0, 0, err
	}

	id, err = exec.LastInsertId()
	if err != nil {
		//fmt.Println("获取此SQL语句执行后返回的主键ID值时发生错误")
		LogError("获取此SQL语句执行后返回的主键ID值时发生错误")
		return 0, 0, err
	}

	return cont, id, nil
}